import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../widgets/platform/adaptive_card.dart';
import '../../../widgets/platform/adaptive_button.dart';
import '../../../widgets/platform/adaptive_text_field.dart';
import '../../../../domain/entities/user.dart';
import '../../../../core/platform/platform_detector.dart';

/// 用户管理页面
class UserManagementPage extends ConsumerStatefulWidget {
  const UserManagementPage({super.key});

  @override
  ConsumerState<UserManagementPage> createState() => _UserManagementPageState();
}

class _UserManagementPageState extends ConsumerState<UserManagementPage> {
  final _searchController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  String _selectedRole = 'DEVELOPER';
  String _selectedStatus = 'ACTIVE';
  String _selectedOrg = '技术部';

  @override
  void initState() {
    super.initState();
    // 初始化时加载用户数据
    _loadUsers();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _loadUsers() {
    // TODO: 实现加载用户数据的逻辑
  }

  void _searchUsers(String query) {
    // TODO: 实现搜索用户逻辑
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 搜索和操作栏
        _buildSearchBar(),
        const SizedBox(height: 16),

        // 用户列表
        Expanded(
          child: _buildUserList(),
        ),
      ],
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: AdaptiveTextField(
              controller: _searchController,
              labelText: '搜索用户',
              prefixIcon: Icons.search,
              hintText: '按用户名、邮箱或角色搜索',
              onChanged: _searchUsers,
            ),
          ),
          const SizedBox(width: 16),
          AdaptiveButton(
            onPressed: _showCreateUserDialog,
            child: const SelectableText('创建用户'),
          ),
        ],
      ),
    );
  }

  Widget _buildUserList() {
    // 模拟用户数据
    final users = [
      User(
        id: 1,
        username: 'admin',
        email: 'admin@flowplan.com',
        role: 'ADMIN',
        orgName: '技术部',
      ),
      User(
        id: 2,
        username: 'zhang_san',
        email: 'zhangsan@flowplan.com',
        role: 'DEVELOPER',
        orgName: '前端组',
      ),
      User(
        id: 3,
        username: 'li_si',
        email: 'lisi@flowplan.com',
        role: 'DEVELOPER',
        orgName: '后端组',
      ),
      User(
        id: 4,
        username: 'product_manager',
        email: 'pm@flowplan.com',
        role: 'DEMANDER',
        orgName: '产品规划组',
      ),
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        // 桌面平台使用表格布局
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
          return _buildDesktopTable(users);
        } else {
          // 移动平台使用卡片列表布局
          return _buildMobileList(users);
        }
      },
    );
  }

  Widget _buildDesktopTable(List<User> users) {
    return SingleChildScrollView(
      child: DataTable(
        columns: const [
          DataColumn(label: SelectableText('用户名')),
          DataColumn(label: SelectableText('邮箱')),
          DataColumn(label: SelectableText('角色')),
          DataColumn(label: SelectableText('组织')),
          DataColumn(label: SelectableText('操作')),
        ],
        rows: users.map((user) => _buildDataRow(user)).toList(),
      ),
    );
  }

  DataRow _buildDataRow(User user) {
    return DataRow(
      cells: [
        DataCell(SelectableText(user.username)),
        DataCell(SelectableText(user.email)),
        DataCell(SelectableText(_getRoleDisplayName(user.role))),
        DataCell(SelectableText(user.orgName ?? '-')),
        DataCell(
          Row(
            children: [
              IconButton(
                icon: const Icon(Icons.edit, size: 20),
                onPressed: () => _showEditUserDialog(user),
              ),
              IconButton(
                icon: const Icon(Icons.delete, size: 20),
                onPressed: () => _showDeleteUserDialog(user),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMobileList(List<User> users) {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: users.length,
      itemBuilder: (context, index) {
        final user = users[index];
        return _buildUserCard(user);
      },
    );
  }

  Widget _buildUserCard(User user) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              CircleAvatar(
                radius: 20,
                backgroundColor: Theme.of(context).primaryColor,
                child: SelectableText(
                  user.username.substring(0, 1).toUpperCase(),
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SelectableText(
                      user.username,
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    SelectableText(
                      user.email,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            color: Colors.grey[600],
                          ),
                    ),
                  ],
                ),
              ),
              PopupMenuButton<String>(
                onSelected: (value) {
                  switch (value) {
                    case 'edit':
                      _showEditUserDialog(user);
                      break;
                    case 'delete':
                      _showDeleteUserDialog(user);
                      break;
                  }
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'edit',
                    child: Row(
                      children: [
                        Icon(Icons.edit, size: 20),
                        SizedBox(width: 8),
                        SelectableText('编辑'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'delete',
                    child: Row(
                      children: [
                        Icon(Icons.delete, size: 20),
                        SizedBox(width: 8),
                        SelectableText('删除'),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              _buildInfoChip(
                Icons.security,
                _getRoleDisplayName(user.role),
                _getRoleColor(user.role),
              ),
              const SizedBox(width: 8),
              if (user.orgName != null)
                _buildInfoChip(
                  Icons.account_balance,
                  user.orgName!,
                  Colors.blue,
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: color),
          const SizedBox(width: 4),
          SelectableText(
            text,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  String _getRoleDisplayName(String role) {
    switch (role) {
      case 'ADMIN':
        return '系统管理员';
      case 'DEVELOPER':
        return '开发人员';
      case 'DEMANDER':
        return '需求方';
      case 'TESTER':
        return '测试人员';
      case 'DBA':
        return '数据库管理员';
      default:
        return role;
    }
  }

  Color _getRoleColor(String role) {
    switch (role) {
      case 'ADMIN':
        return Colors.red;
      case 'DEVELOPER':
        return Colors.blue;
      case 'DEMANDER':
        return Colors.green;
      case 'TESTER':
        return Colors.orange;
      case 'DBA':
        return Colors.purple;
      default:
        return Colors.grey;
    }
  }

  void _showCreateUserDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('创建用户'),
        content: _buildUserForm(),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleCreateUser,
            child: const SelectableText('创建'),
          ),
        ],
      ),
    );
  }

  void _showEditUserDialog(User user) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('编辑用户'),
        content: _buildUserForm(user: user),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleUpdateUser,
            child: const SelectableText('保存'),
          ),
        ],
      ),
    );
  }

  void _showDeleteUserDialog(User user) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: SelectableText('确定要删除用户 "${user.username}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _handleDeleteUser(user);
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const SelectableText('删除'),
          ),
        ],
      ),
    );
  }

  Widget _buildUserForm({User? user}) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AdaptiveTextField(
            labelText: '用户名',
            prefixIcon: Icons.person,
            initialValue: user?.username ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入用户名';
              }
              if (value.length < 3) {
                return '用户名长度不能少于3位';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          AdaptiveTextField(
            labelText: '邮箱',
            prefixIcon: Icons.email,
            initialValue: user?.email ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入邮箱';
              }
              if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
                  .hasMatch(value)) {
                return '请输入有效的邮箱地址';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            initialValue: _selectedOrg,
            decoration: const InputDecoration(
              labelText: '所属组织',
              border: OutlineInputBorder(),
            ),
            readOnly: true,
            onTap: () => _showOrgSelector(context),
          ),
          const SizedBox(height: 16),
          TextFormField(
            initialValue: _selectedRole,
            decoration: const InputDecoration(
              labelText: '角色',
              border: OutlineInputBorder(),
            ),
            readOnly: true,
            onTap: () => _showRoleSelector(context),
          ),
          const SizedBox(height: 16),
          // 组织选择
          DropdownButtonFormField<String>(
            initialValue: _selectedStatus,
            decoration: const InputDecoration(
              labelText: '状态',
              border: OutlineInputBorder(),
            ),
            items: const [
              DropdownMenuItem(
                value: 'ACTIVE',
                child: SelectableText('激活'),
              ),
              DropdownMenuItem(
                value: 'INACTIVE',
                child: SelectableText('禁用'),
              ),
            ],
            onChanged: (value) {
              setState(() {
                _selectedStatus = value!;
              });
            },
          )
        ],
      ),
    );
  }

  void _handleCreateUser() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现创建用户逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('用户创建成功')),
      );
    }
  }

  void _handleUpdateUser() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现更新用户逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('用户信息更新成功')),
      );
    }
  }

  void _handleDeleteUser(User user) {
    // TODO: 实现删除用户逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: SelectableText('用户"${user.username}"删除成功')),
    );
  }

  void _showOrgSelector(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('选择组织'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const SelectableText('技术部'),
              onTap: () {
                setState(() {
                  _selectedOrg = '技术部';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('前端组'),
              onTap: () {
                setState(() {
                  _selectedOrg = '前端组';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('后端组'),
              onTap: () {
                setState(() {
                  _selectedOrg = '后端组';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('产品规划组'),
              onTap: () {
                setState(() {
                  _selectedOrg = '产品规划组';
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showRoleSelector(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('选择角色'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const SelectableText('系统管理员'),
              onTap: () {
                setState(() {
                  _selectedRole = 'ADMIN';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('开发人员'),
              onTap: () {
                setState(() {
                  _selectedRole = 'DEVELOPER';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('需求方'),
              onTap: () {
                setState(() {
                  _selectedRole = 'DEMANDER';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('测试人员'),
              onTap: () {
                setState(() {
                  _selectedRole = 'TESTER';
                });
                Navigator.of(context).pop();
              },
            ),
            ListTile(
              title: const SelectableText('数据库管理员'),
              onTap: () {
                setState(() {
                  _selectedRole = 'DBA';
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
    );
  }
}
